package com.wx.job;

import com.wx.constants.Constants;
import com.wx.entity.SysCron;
import com.wx.exception.BusinessException;
import com.wx.service.SysCronService;
import com.wx.service.SysPatientFollowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Configuration
@EnableScheduling
@Slf4j
public class FollowRemindJob implements SchedulingConfigurer {

    @Resource
    private SysCronService sysCronService;

    @Resource
    private SysPatientFollowService sysPatientFollowService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> {
                    sysPatientFollowService.remind();
                },
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    SysCron sysCronDB = new SysCron();
                    sysCronDB.setId(Constants.Cron.FOLLOW_REMIND);
                    sysCronDB.setDelFlag(Constants.DELETE_NO);
                    SysCron sysCron = sysCronService.selectOne(sysCronDB);
                    if(sysCron == null || StringUtils.isEmpty(sysCron.getCron())){
                        throw new BusinessException("随访提醒任务失败");
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(sysCron.getCron()).nextExecutionTime(triggerContext);
                }
        );
    }
}
